﻿/// <reference path="~/app/libs/sencha-touch-all.js" />
Ext.define("iMobileS.controller.MobileS", {
    extend: "Ext.app.Controller",
    config: {
        refs: {
            categoriesContainer: 'categoriescontainer',
            productsContainer: 'productscontainer',
            productDetailsContainer: 'productdetailscontainer',
            customerContainer: 'customercontainer',
            checkoutContainer: 'checkoutcontainer'
        },
        control: {
            categoriesContainer: {
                onCategoriesDiscloseChanged: "doCategoriesDiscloseChanged",
                onCategoriesSelectedChanged: "doCategoriesSelectedChanged"
            },
            productsContainer: {
                onBackToCategories: "doBackToCategories",
                onProductsDiscloseChanged: "doProductsDiscloseChanged",
                onProductsSelectedChanged: "doProductsSelectedChanged",
                onCheckOutClick: 'doCheckOutClick'
            },
            productDetailsContainer: {
                onBackToProducts: "doBackToProducts",
                onSaveProductDetails: "doSaveProductDetails"
            },
            customerContainer: {
                onBackToCheckoutContainer: "onBackToCheckoutContainer",
                onBackToHome: 'doBackToHome'
            },
            checkoutContainer: {
                onBackToHome: 'doBackToHome',
                onSelectCustomer: 'doSelectCustomer'
            }
        }
    },
    launch: function () {
        this.callParent(arguments);
        Ext.getStore("Categories").load();
    },
    init: function () {
        this.callParent(arguments);
    },
    // Transitions
    slideLeftTransition: { type: 'slide', direction: 'left' },
    slideRightTransition: { type: 'slide', direction: 'right' },
    /*
    * FUNCTION: Choice categories to get products by category id
    * MOVE to form products
    */
    doCategoriesDiscloseChanged: function (list, record, target, index, evt, options) {

    },
    /*
    * FUNCTION: Highlight categories was selected
    */
    doCategoriesSelectedChanged: function (list, index) {
        var cId = list.getStore().getAt(index).data.CategoryID;
        Ext.getStore('Products').load({
            params: { cateId: cId },
            callback: function (records, operation, success) {
                var productsContainer = this.getProductsContainer();
                Ext.Viewport.animateActiveItem(productsContainer, this.slideLeftTransition);
            },
            scope: this
        });
    },
    /*
    * FUNCTION: Back to categories form
    */
    doBackToCategories: function () {
        var categoriesContainer = this.getCategoriesContainer();
        Ext.Viewport.animateActiveItem(categoriesContainer, this.slideRightTransition);
    },
    /*
    * FUNCTION:doProductsDiscloseChanged
    * DESCRIPTION: Event of product changed
    */
    doProductsDiscloseChanged: function (list, record, target, index, evt, options) {

    },
    /*
    * FUNCTION
    *
    */
    doProductsSelectedChanged: function (list, index) {
        var pId = list.getStore().getAt(index).data.ProductID;
        var pName = list.getStore().getAt(index).data.ProductName;
        var uniPrice = list.getStore().getAt(index).data.UnitPrice;
        var quantity = list.getStore().getAt(index).data.QuantityPerUnit;
        Ext.getCmp('RecordIndex').setHtml(index);
        Ext.getCmp('ProductID').setValue(pId);
        Ext.getCmp('ProductName').setValue(pName);
        Ext.getCmp('UnitPrice').setValue(uniPrice);
        Ext.getCmp('QuantityPerUnit').setValue(quantity);
        var productDetailsContainer = this.getProductDetailsContainer();
        Ext.Viewport.animateActiveItem(productDetailsContainer, this.slideLeftTransition);
    },
    /*
    * FUNCTION: Back to order form
    */
    doBackToProducts: function () {
        var productsContaienr = this.getProductsContainer();
        Ext.Viewport.animateActiveItem(productsContaienr, this.slideRightTransition);
    },
    /*
    * FUNCTION: Save information to database
    * DESCIPTION: here: save order, order detail, customer, shipper tables
    * MUST USE: Transaction to insert data to database
    */
    doSaveProductDetails: function (quantity, total) {
        var recordIndex = Ext.getCmp('RecordIndex').getHtml();        
        var record = Ext.getStore("Products").getAt(recordIndex);
        record.setData({
            'ProductID': record.get('ProductID'),
            'ProductName': record.get('ProductName'),
            'Description': record.get('Description'),
            'SupplierID': record.get('SupplierID'),
            'CategoryID': record.get('CategoryID'),
            'QuantityPerUnit': record.get('QuantityPerUnit'),
            'UnitPrice': record.get('UnitPrice'),
            'UnitsInStock': record.get('UnitsInStock'),
            'UnitsOnOrder': record.get('UnitsOnOrder'),
            'ReorderLevel': record.get('ReorderLevel'),
            'Discontinued': record.get('Discontinued'),
            'Quantity': quantity,
            'Discount': record.get('Discount') == null ? 0 : record.get('Discount'),
            'Total': total
        });
        this.doBackToProducts();
    },
    /*
    * FUNCTION: Move to form customer info
    * DESCRIPTIONM: User have to fill out their information
    */
    doSelectCustomer: function () {
        Ext.getStore("Employees").load();
        Ext.getStore("Customers").load();
        Ext.getStore("Shippers").load();
        Ext.getStore("Regions").load({
            callback: function (records, operation, success) {
                var customerContainer = this.getCustomerContainer();
                Ext.Viewport.animateActiveItem(customerContainer, this.slideLeftTransition);
            },
            scope: this
        });
    },
    /*
    *
    */
    doBackToHome: function () {
        var categoriesContainer = this.getCategoriesContainer();
        Ext.Viewport.animateActiveItem(categoriesContainer, this.slideRightTransition);
        Ext.getStore("Products").clearFilter();
    },
    /*
    *
    */
    doCheckOutClick: function () {
        Ext.getStore("Products").filterBy(function (record) {
            if (record.get("Quantity") != null) {
                return record;
            }
            else {
                return false;
            }
        });
        if (Ext.getStore("Products").getCount() > 0) {
            var objProducts = Ext.getStore("Products");
            var count = objProducts.getCount();
            var totalHandling = 0;
            var totalOrder = 0;
            for (var i = 0; i < count; i++) {
                var record = objProducts.getAt(i);
                var discount = record.data.Discount;
                totalHandling += discount;
                var total = record.data.Total;
                totalOrder += total;
            }
            Ext.getCmp('Handling').setValue(totalHandling);
            Ext.getCmp('OrderTotal').setValue(totalOrder);
            var checkoutContainer = this.getCheckoutContainer();
            Ext.Viewport.animateActiveItem(checkoutContainer, this.slideLeftTransition);
        }
        else {
            Ext.getStore("Products").clearFilter();
            Ext.Msg.alert('', 'Please select products', Ext.emptyFn);
        }
    },
    /*
    *
    */
    onBackToCheckoutContainer: function () {
        var checkoutContainer = this.getCheckoutContainer();
        Ext.Viewport.animateActiveItem(checkoutContainer, this.slideRightTransition);
    }
});